package org.csu.myPetStore.persistence.impl;

import org.csu.myPetStore.domain.CloseSource;
import org.csu.myPetStore.domain.LineItem;
import org.csu.myPetStore.persistence.DBUtil;
import org.csu.myPetStore.persistence.LineItemDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class LineItemDAOImpl implements LineItemDAO {

    private static final String GET_LINE_ITEM_BY_ORDERID = "SELECT ORDERID,LINENUM AS lineNumber, ITEMID,QUANTITY,UNITPRICE FROM LINEITEM WHERE ORDERID = ?";
    private static final String INSERT_LINE_ITEM = " INSERT INTO LINEITEM (ORDERID, LINENUM, ITEMID, QUANTITY, UNITPRICE) VALUES (?,?,?,?,?)";

    //显示订单信息
    @Override
    public List<LineItem> getLineItemsByOrderId(int orderId) {
        List<LineItem> lineItemList = new ArrayList<LineItem>();
        String ordId = orderId+"";

        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(GET_LINE_ITEM_BY_ORDERID);
            preparedStatement.setString(1,ordId);
            ResultSet resultSet = preparedStatement.executeQuery();

            while(resultSet.next()){
                LineItem lineItem = new LineItem();
                lineItem.setOrderId(resultSet.getInt(1));
                lineItem.setLineNumber(resultSet.getInt(2));
                lineItem.setItemId(resultSet.getString(3));
                lineItem.setQuantity(resultSet.getInt(4));
                lineItem.setUnitPrice(resultSet.getBigDecimal(5));
                lineItemList.add(lineItem);
            }

            CloseSource closeSource = new CloseSource();
            closeSource.closeSource(connection,preparedStatement,resultSet,null);

        }catch (Exception e){
            e.printStackTrace();
        }

        return lineItemList;
    }

    //插入订单信息进入MyCount
    @Override
    public void insertLineItem(LineItem lineItem) {
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(INSERT_LINE_ITEM);
            preparedStatement.setInt(1,lineItem.getOrderId());
            preparedStatement.setInt(2,lineItem.getLineNumber());
            preparedStatement.setString(3,lineItem.getItemId());
            preparedStatement.setInt(4,lineItem.getQuantity());
            preparedStatement.setBigDecimal(5,lineItem.getUnitPrice());

            int result = preparedStatement.executeUpdate();
            if(result == 1)
                System.out.println("insertLineItem 成功");

            CloseSource closeSource = new CloseSource();
            closeSource.closeSource(connection,preparedStatement,null,null);

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
